package com.hk.core.springdoc.openapi;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.tags.Tag;
import org.apache.commons.io.IOUtils;
import org.springdoc.core.customizers.OpenApiBuilderCustomizer;
import org.springdoc.core.customizers.ServerBaseUrlCustomizer;
import org.springdoc.core.properties.SpringDocConfigProperties;
import org.springdoc.core.providers.JavadocProvider;
import org.springdoc.core.service.OpenAPIService;
import org.springdoc.core.service.SecurityService;
import org.springdoc.core.utils.PropertyResolverUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;

import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;

/**
 * 基于java 注释生成文档
 */
public class JavaDocOpenAPIService extends OpenAPIService {

    public JavaDocOpenAPIService(OpenAPI openAPI, SecurityService securityParser,
                                 SpringDocConfigProperties springDocConfigProperties,
                                 PropertyResolverUtils propertyResolverUtils,
                                 List<OpenApiBuilderCustomizer> openApiBuilderCustomizers,
                                 List<ServerBaseUrlCustomizer> serverBaseUrlCustomizers,
                                 JavadocProvider javadocProvider) {
        super(Optional.ofNullable(openAPI), securityParser, springDocConfigProperties, propertyResolverUtils,
                Optional.ofNullable(openApiBuilderCustomizers), Optional.ofNullable(serverBaseUrlCustomizers),
                Optional.ofNullable(javadocProvider));
    }

    /**
     * 父类默认没有使用类名上的注释，这里改写
     */
    @Override
    public Operation buildTags(HandlerMethod handlerMethod, Operation operation, OpenAPI openAPI, Locale locale) {
        Operation res = super.buildTags(handlerMethod, operation, openAPI, locale);
        List<Tag> tags = openAPI.getTags();
        if (CollectionUtils.isEmpty(tags)) {
            return res;
        }
        String tagName = splitCamelCase(handlerMethod.getBeanType().getSimpleName());
        tags.stream()
                .filter(item -> Objects.equals(item.getName(), tagName) && StringUtils.hasLength(item.getDescription()))
                .findFirst()
                .ifPresent(tag -> {
                    List<String> list = IOUtils.readLines(tag.getDescription());
                    tag.setName(list.getFirst());
                    res.setTags(list);
                });
        return res;
    }
}
